package frame.usermeau.service.serviceimpl;

import frame.model.SnowflakeIdWorker;
import frame.usermeau.service.ServiceFrame;
import javafx.scene.control.TableColumn;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ProductServiceFrame extends ServiceFrame {

    private String userId;

    public ProductServiceFrame(String userId) {
        super();
        this.userId = userId;
    }

    public void padding(JTextArea jTextArea) {
        init();
        Table table = null;

        List<String> productIdList = new ArrayList<>();
        List<String> productNameList = new ArrayList<>();
        List<String> productDescriptionList = new ArrayList<>();
        List<String> productPeriodList = new ArrayList<>();
        try {
            PreparedStatement preparedStatement = conn.prepareStatement("select fp_id, fp_name, fp_description, fp_period, fp_is_on_sale from t_product");
            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                String productId = resultSet.getString(1);
                String productName = resultSet.getString(2);
                String productDescription = resultSet.getString(3);
                String productPeriod = resultSet.getString(4);
                boolean isOnSale = resultSet.getBoolean(5);
                if (isOnSale) {
                    productIdList.add(productId);
                    productNameList.add(productName);
                    productDescriptionList.add(productDescription);
                    productPeriodList.add(productPeriod + "月");
                }
            }
            table = Table.create("相关理财产品").addColumns(
                    StringColumn.create("产品ID",productIdList),
                    StringColumn.create("产品名称",productNameList),
                    StringColumn.create("产品描述",productDescriptionList),
                    StringColumn.create("产品周期",productPeriodList)
            );
            jTextArea.setText(table.print());
            resultSet.close();
            preparedStatement.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示导航栏，固定不改变
     * @return
     */
    @Override
    public JPanel showOptions() {
        JPanel jPanel = new JPanel(null);

        JLabel jl;
        //投资期限
        jl = new JLabel("投资期限:");
        jl.setSize(80,20);
        jl.setLocation(30,20);
        jPanel.add(jl);
        JTextArea inputPeriod = new JTextArea();
        inputPeriod.setSize(100,20);
        inputPeriod.setLocation(100,20);
        jPanel.add(inputPeriod);
        jl = new JLabel("月");
        jl.setSize(80,20);
        jl.setLocation(200,20);
        jPanel.add(jl);

        //名称
        jl = new JLabel("名称:");
        jl.setSize(80,20);
        jl.setLocation(300,20);
        jPanel.add(jl);
        JTextArea inputName = new JTextArea();
        inputName.setSize(150,20);
        inputName.setLocation(350,20);
        jPanel.add(inputName);

        //确认按钮
        JButton jButton = new JButton("确认");
        jButton.setSize(60,40);
        jButton.setLocation(400,50);
        jPanel.add(jButton);

        //结果框
        JTextArea result = new JTextArea();
        result.setSize(450, 500);
        result.setLocation(30,100);
        jPanel.add(result);
        padding(result);

        jButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String period = inputPeriod.getText();
                String name = inputName.getText();
                Table strs;
                if (cal(period)) {
                    strs = showMessage(period, name);
                    result.setText(strs.print());
                }else {
                    JOptionPane.showMessageDialog(null, "月数输入的格式不正确");
                }
            }
        });

        return jPanel;
    }


    /**
     * 返回结果
     * @param date 年龄
     * @param name 名称
     */
    private Table showMessage(String date, String name) {
        date = date.trim();
        name = name.trim();
        init();
        Table table = null;

        List<String> productIdList = new ArrayList<>();
        List<String> productNameList = new ArrayList<>();
        List<String> productDescriptionList = new ArrayList<>();
        List<String> productPeriodList = new ArrayList<>();
        if ("".equals(date)) {
            try {
                PreparedStatement preparedStatement = conn.prepareStatement("select fp_id, fp_name, fp_description, fp_period, fp_is_on_sale from t_product where fp_name like '%'||?||'%' ;");
                preparedStatement.setString(1, name);
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    String productId = resultSet.getString(1);
                    String productName = resultSet.getString(2);
                    String productDescription = resultSet.getString(3);
                    String productPeriod = resultSet.getString(4);
                    boolean isOnSale = resultSet.getBoolean(5);
                    if (isOnSale) {
                        productIdList.add(productId);
                        productNameList.add(productName);
                        productDescriptionList.add(productDescription);
                        productPeriodList.add(productPeriod + "月");
                    }
                }
                table = Table.create("相关理财产品").addColumns(
                        StringColumn.create("产品ID",productIdList),
                        StringColumn.create("产品名称",productNameList),
                        StringColumn.create("产品描述",productDescriptionList),
                        StringColumn.create("产品周期",productPeriodList)
                );
                resultSet.close();
                preparedStatement.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else {
            try {
                PreparedStatement preparedStatement = conn.prepareStatement("select fp_id, fp_name, fp_description, fp_period, fp_is_on_sale from t_product where fp_name like '%'||?||'%' and fp_period <= ?;");
                preparedStatement.setString(1, name);
                preparedStatement.setInt(2, Integer.parseInt(date));
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    String productId = resultSet.getString(1);
                    String productName = resultSet.getString(2);
                    String productDescription = resultSet.getString(3);
                    String productPeriod = resultSet.getString(4);
                    boolean isOnSale = resultSet.getBoolean(5);
                    if (isOnSale) {
                        productIdList.add(productId);
                        productNameList.add(productName);
                        productDescriptionList.add(productDescription);
                        productPeriodList.add(productPeriod + "月");
                    }
                }
                table = Table.create("相关理财产品").addColumns(
                        StringColumn.create("产品ID",productIdList),
                        StringColumn.create("产品名称",productNameList),
                        StringColumn.create("产品描述",productDescriptionList),
                        StringColumn.create("产品周期",productPeriodList)
                );
                resultSet.close();
                preparedStatement.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return table;
    }

    /**
     * 购买产品
     * @param name      产品名称
     * @param number    购买数目
     */
    @Override
    public void purchase(String name, Integer number) {
        name = name.trim();

        if (isTrueProduct(name)) {
            init();
            BigDecimal buy = new BigDecimal(number);
            BigDecimal limit = new BigDecimal(-1000);

            // 卡号和卡里面的钱
            String useCard = null;
            BigDecimal moneyInCard = null;
            try {
                PreparedStatement getAllCards = conn.prepareStatement("select c_id, c_type, c_balance from t_card where c_user_id = ?");
                getAllCards.setString(1, userId);
                ResultSet resultSet = getAllCards.executeQuery();
                while (resultSet.next()) {
                    String cardId = resultSet.getString(1);
                    int typeCard = resultSet.getInt(2);
                    BigDecimal cardMoney = resultSet.getBigDecimal(3);
                    if (typeCard == 0) {
                        // 储蓄卡
                        if (cardMoney.compareTo(buy) >= 0) {
                            useCard = cardId;
                            moneyInCard = cardMoney;
                            break;
                        }
                    }else {
                        // 信用卡
                        if (cardMoney.subtract(buy).compareTo(limit) >= 0) {
                            useCard = cardId;
                            moneyInCard = cardMoney;
                            break;
                        }
                    }
                }
                conn.close();
                getAllCards.close();
                resultSet.close();

                if (useCard == null) {
                    JOptionPane.showMessageDialog(null, "账户金额不足！");
                }else{
                    // 事务
                    init();
                    conn.setAutoCommit(false);

                    PreparedStatement updateCard = conn.prepareStatement("update t_card set c_balance = c_balance - ? where c_id = ? ");
                    PreparedStatement purseProduct = conn.prepareStatement("insert into t_proassets(fpa_id, fpa_status, fpa_amount, fpa_income, fpa_date, fpa_user_id, fpa_product_id) values(?,?,?,?,now(),?,?)");
                    PreparedStatement recordMent = conn.prepareStatement("insert into t_transaction(tra_id, tra_amount, tra_time, tra_card_id) values(?,?,now(),?)");

                    updateCard.setInt(1,buy.intValue());
                    updateCard.setString(2, useCard);

                    purseProduct.setString(1, idWorker.nextId() + "66");
                    purseProduct.setInt(2,1);
                    purseProduct.setBigDecimal(3,buy);
                    purseProduct.setBigDecimal(4,new BigDecimal(0));
                    purseProduct.setString(5,userId);
                    purseProduct.setString(6,name);

                    recordMent.setString(1, idWorker.nextId() + "88");
                    recordMent.setDouble(2, buy.doubleValue() * (-1));
                    recordMent.setString(3, useCard);

                    updateCard.executeUpdate();
                    purseProduct.execute();
                    recordMent.execute();
                    conn.commit();

                    updateCard.close();
                    purseProduct.close();
                    recordMent.close();
                    conn.close();

                    this.dispose();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    Connection conn;
    SnowflakeIdWorker idWorker;
    public void init() {
        try {
            Class.forName("org.opengauss.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection("jdbc:opengauss://121.36.41.207:26000/finance", "geqiyu", "Tlyz0729");


        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            // 设置demo为搜索路径
            PreparedStatement firstStep = conn.prepareStatement("SET SEARCH_PATH TO db1,public");
            firstStep.execute();
            firstStep.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        idWorker = new SnowflakeIdWorker(0, 0);
    }

    public boolean isTrueProduct(String productId) {
        if (productId.length() != 20) {
            JOptionPane.showMessageDialog(null, "理财产品ID输入格式不对，请重新输入");
            return false;
        }else{
            init();
            try {
                PreparedStatement preparedStatement = conn.prepareStatement("select fp_id from t_product where fp_id = ?");
                preparedStatement.setString(1,productId);
                ResultSet resultSet = preparedStatement.executeQuery();
                if (resultSet.next()) {
                    return true;
                }
                conn.close();
                resultSet.close();
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JOptionPane.showMessageDialog(null, "没有以此为ID的基金");
            return false;
        }
    }


}
